/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.cicp.collector.emc;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.CommandReader;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * <p>
 * Description: ctlIp:控制端的IP sid:存储的ID号 sympath:Solutions
 * Enabler的安装路径-用来查询存储信息的命令路径 --上三个属性 lastDate:最后一个已获取事件的时间+1秒
 
 cmd=cd /usr/symcli/bin;./symevent -sid 000498700015
 * </p>
 
 
 * 
 * @author wangyazhou
 * @version 1.0
 * 
 *          <p>
 *          History:
 * 
 *          Date Author Version Description
 *          --------------------------------------
 *          ------------------------------------------- 2013-7-22 下午2:31:11
 *          wangyazhou 1.0 To create
 *          </p>
 * 
 * @since
 * @see
 */
public class FaultEventCollector extends Collector {

    private static final Logger logger = Logger.getLogger("prop");

    private static SimpleDateFormat sf = new SimpleDateFormat("MM/dd/yyyy':'HH:mm:ss");

    private static SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String ctlIp = this.getParamMap().get("ctlIp");
        String sid = this.getParamMap().get("sid");

        String symPath = this.getParamMap().get("symPath");

        String[] propMetas = getPropMeta();
        String cmd = "";
        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        ResPropertyValue propertyValueX = null;
        ResPropertyValue.PropValue[] propValues = null;

        // 获取上次采集时间 如果没值 则设为当前时间
        String lastTime = "";
        String currentTime = sf.format(Calendar.getInstance().getTime());
        String newLastTime = "";
        try {
            lastTime = getEmcEventDate(sid);
        } catch (Exception e) {
            lastTime = currentTime;
        }

        if (lastTime == null || lastTime.length() < 1) {
            lastTime = currentTime;
        }

        BufferedReader reader = null;
        try {

            cmd = "cd " + symPath.trim() + " && ./symevent -sid " + sid + " list -v  -start " + lastTime + " -end " + currentTime;
            // cmd = "cd " + symPath.trim() + " && ./symevent -sid " + sid
            // + " list -v  -start 07/18/2013:00:00:00 -end "
            // + currentTime;

            reader = CommandReader.getReader(ctlIp, cmd, 0, 0);
            StringBuilder sb = new StringBuilder();
            while (true) {
                String line = reader.readLine();
                if (line == null)
                    break;
                sb.append(line);
            }
            logger.info("ip[" + ip + "]\t" + "cmd[" + cmd + "]\n" + "result[" + sb.toString() + "]");
            String[] symresults = Pattern.compile("Symmetrix\\s+ID:").split(sb);
            SimpleDateFormat df = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.ENGLISH);

            List<Event> emcevents = new ArrayList<Event>();
            for (int i = 1; i < symresults.length; i++) {
                String[] eventresults = Pattern.compile("Event\\s+at").split(symresults[i]);
                Matcher mat = Pattern.compile("(.*)Time\\s+Zone").matcher(eventresults[0]);
                String symmetrix = "";
                while (mat.find()) {
                    symmetrix = mat.group(1).trim();
                }
                for (int j = 1; j < eventresults.length; j++) {
                    Matcher matcher = Pattern.compile("\\s*(.+):\\s*Reporting\\s*Director\\s*:(.+)Source\\s*:(.+)Category\\s*:\\s*+(\\S+)\\s*+(Symmetrix\\s*Device\\s*:(.+))?Severity\\s*:(.+)Numeric\\s*Code\\s*:(.+)Event\\s*Code\\s*Symbol\\s*:(.+)Description\\s*:(.*)$").matcher(eventresults[j]);
                    while (matcher.find()) {
                        Event event = new Event();
                        event.setSid(symmetrix);
                        event.setRepDir(matcher.group(2).trim());
                        event.setSource(matcher.group(3).trim());
                        event.setCategory(matcher.group(4).trim());
                        event.setDevice(matcher.group(6) == null ? null : matcher.group(6).trim());
                        event.setSeverity(EventSeverity.parseEventSeverity(matcher.group(7).trim()));
                        event.setNumCode(matcher.group(8).trim());
                        event.setEventCode(matcher.group(9).trim());
                        event.setDesc(matcher.group(10).trim());
                        event.setDate(df.parse(matcher.group(1).trim()));
                        emcevents.add(event);

                    }
                }
            }

            for (int i = 0; i < emcevents.size(); i++) {
                Event e = emcevents.get(i);
                propertyValueX = new ResPropertyValue();
                propValues = new ResPropertyValue.PropValue[9];
                propValues[0] = ResPropertyValue.createPropValue(e.getRepDir(), propMetas[0]);
                propValues[1] = ResPropertyValue.createPropValue(e.getSource(), propMetas[1]);
                propValues[2] = ResPropertyValue.createPropValue(e.getCategory(), propMetas[2]);
                propValues[3] = ResPropertyValue.createPropValue(e.getDevice(), propMetas[3]);
                propValues[4] = ResPropertyValue.createPropValue(e.getSeverity().toString(), propMetas[4]);
                propValues[5] = ResPropertyValue.createPropValue(e.getNumCode(), propMetas[5]);
                propValues[6] = ResPropertyValue.createPropValue(e.getEventCode(), propMetas[6]);
                propValues[7] = ResPropertyValue.createPropValue(e.getDesc(), propMetas[7]);
                propValues[8] = ResPropertyValue.createPropValue(outFormat.format(e.getDate()), propMetas[8]);
                propertyValueX.setValues(propValues);
                values.add(propertyValueX);
                if (i == emcevents.size() - 1) {
                    try {
                        //newLastTime = sf.format(e.getDate());
                        lastTime = sf.format(e.getDate());
                    } catch (Exception e2) {
                        //newLastTime = currentTime;
                        lastTime = currentTime;
                    }
                }
            }
            //			if (newLastTime == null || newLastTime.length() < 1) {
            //				newLastTime = currentTime;
            //			}
            if (lastTime == null || lastTime.length() < 1) {
                lastTime = currentTime;
            }

            //String timeStr = datePlusSecond(newLastTime);
            String timeStr = datePlusSecond(lastTime);
            saveEmcEventDate(sid, timeStr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return values;
    }

    @Override
    public String[] getPropMeta() {
        return new String[] { "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" };
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "sid", "ctlIp", "symPath" };
    }

    private String datePlusSecond(String currentTime) throws Exception {
        Date od = sf.parse(currentTime);
        Calendar cal = Calendar.getInstance();
        cal.setTime(od);
        cal.add(Calendar.SECOND, 1);

        return sf.format(cal.getTime());
    }

    private String getEmcEventDate(String ip) throws IOException {
        String fileName = "save/" + ip + "_EMC.od";
        File file = new File(fileName);
        if (!file.exists()) {
            return null;
        }
        return FileUtils.readFileToString(file);
    }

    private static void saveEmcEventDate(String ip, String date) throws IOException {
        File saveDir = new File("save");
        if (!saveDir.exists()) {
            saveDir.mkdir();
        }
        String fileName = "save/" + ip + "_EMC.od";
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                logger.error("failed to create new file", e);
            }
        }
        FileUtils.writeStringToFile(file, date);
    }

    public static void main(String[] args) {
        try {

            String ip = "000287750558";
            String date = "07/28/2013:15:31:05";
            saveEmcEventDate(ip, date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
